﻿/**************************************************************
 * Copyright gt1987. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/4/14 14:35:57
 * Description: UniqueIdPerDayCountValidator
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using gt.ShortMessage.Services.Validators;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace gt.ShortMessage.Services.Impls
{
    public class UniqueIdPerDayCountValidator : IUniqueIdValidator
    {
        private readonly int _maxCountPerDay = 10;
        private readonly IMemoryCache _cache = null;
        private readonly string _keyPrefix = "uniqueId:count:perday:";

        public UniqueIdPerDayCountValidator(IMemoryCache cache)
        {
            _cache = cache;
        }

        public void Statistics(string uniqueId)
        {
            var key = string.Concat(_keyPrefix, uniqueId);
            int currentCount = 0;
            //这里不严谨，只是简单处理。实际需要原子性处理
            if (_cache.TryGetValue(key, out currentCount))
            {
                currentCount++;
                _cache.Set(key, currentCount,DateTime.Now.AddDays(1).Date);
            }
        }

        public bool Validate(string uniqueId)
        {
            if (string.IsNullOrEmpty(uniqueId)) return false;
            int currentCount = 0;
            if (_cache.TryGetValue(string.Concat(_keyPrefix, uniqueId), out currentCount))
            {
                return currentCount <= _maxCountPerDay;
            }
            return true;
        }
    }
}
